package com.maltys.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author malty
 * @link <a href="https://leetcode.cn/problems/combination-sum-ii/description/">组合总数2</a>
 */
public class CombinationsSumII {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        backTracing(candidates, new int[candidates.length], target, 0, 0, new ArrayList<>(), res);
        return res;
    }

    public void backTracing(int[] candidates, int[] used, int target, int sum, int idx, List<Integer> list, List<List<Integer>> res) {
        if (sum == target) {
            res.add(new ArrayList<>(list));
            return;
        }
        if (sum > target || idx >= candidates.length) {
            return;
        }

        for (int i = idx; i < candidates.length; i++) {
            if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == 0) {
                continue;
            }
            list.add(candidates[i]);
            used[i] = 1;
            backTracing(candidates, used, target, sum + candidates[i], i + 1, list, res);
            list.remove(list.size() - 1);
            used[i] = 0;
        }
    }

    public static void main(String[] args) {
        CombinationsSumII combinationsII = new CombinationsSumII();
        List<List<Integer>> lists = combinationsII.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8);
        lists.forEach(e -> System.out.println(e));
    }
}
